package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmdp.Rabbitmq.MqSender;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.User;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.mapper.VoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lbe
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserMapper userMapper;
    @Resource
    private VoucherMapper voucherMapper;
    @Resource
    private SeckillVoucherMapper seckillVoucherMapper;
    @Resource
    private MqSender mqSender;

    private static final String SALT = "randomString";

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT =new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //创建线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
/*        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());*/
    }
    private static final Logger LOGGER = LoggerFactory.getLogger(VoucherOrderServiceImpl.class);

    @Override
    public int createVerifiedOrder(Integer sid, Integer userId, String verifyHash) throws Exception {

        // 验证是否在抢购时间内
        LOGGER.info("请自行验证是否在抢购时间内,假设此处验证成功");

        // 验证hash值合法性
        String hashKey = RedisConstants.HASH_KEY + "_" + sid + "_" + userId;
        String verifyHashInRedis = stringRedisTemplate.opsForValue().get(hashKey);
        if (!verifyHash.equals(verifyHashInRedis)) {
            throw new Exception("hash值与Redis中不符合");
        }
        LOGGER.info("验证hash值合法性成功");

        // 检查用户合法性
        User user = userMapper.selectById(userId.longValue());
        if (user == null) {
            throw new Exception("用户不存在");
        }
        LOGGER.info("用户信息验证成功：[{}]", user.toString());

        // 检查商品合法性
        Voucher stock = voucherMapper.selectById(sid);
        if (stock == null) {
            throw new Exception("商品不存在");
        }
        LOGGER.info("商品信息验证成功：[{}]", stock.toString());

        //乐观锁更新库存
        LOGGER.info("乐观锁更新库存成功");

        //创建订单
        LOGGER.info("创建订单成功");

        return 1;
    }
    @Override
    public String getVerifyHash(Integer sid, Integer userId) throws Exception {

        // 验证是否在抢购时间内
        LOGGER.info("验证是否在抢购时间内");

        // 检查用户合法性
        User user = userMapper.selectById(userId.longValue());
        if (user == null) {
            throw new Exception("用户不存在");
        }
        LOGGER.info("用户信息：[{}]", user.toString());

        // 检查商品合法性
        Voucher stock = voucherMapper.selectById(sid);
        if (stock == null) {
            throw new Exception("商品不存在");
        }
        LOGGER.info("商品信息：[{}]", stock.toString());

        // 生成hash
        String verify = SALT + sid + userId;
        String verifyHash = DigestUtils.md5DigestAsHex(verify.getBytes());

        // 将hash和用户商品信息存入redis
        String hashKey = RedisConstants.HASH_KEY + "_" + sid + "_" + userId;
        stringRedisTemplate.opsForValue().set(hashKey, verifyHash, 3600, TimeUnit.SECONDS);
        LOGGER.info("Redis写入：[{}] [{}]", hashKey, verifyHash);
        return verifyHash;
    }

    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    //获取消息队列中的订单信息XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAM s1 >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    //判断订单信息是否为空
                    if(list == null || list.isEmpty()){
                        //为空继续循环
                        continue;
                    }
                    //解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //创建订单
                    createVoucherOrder(voucherOrder);
                    //确认消息
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1",record.getId());

                } catch (Exception e) {
                    log.error("处理订单异常");
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true){
                try {
                    //获取消息队列中的订单信息XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAM s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    //判断订单信息是否为空
                    if(list == null || list.isEmpty()){
                        //为空结束
                        break;
                    }
                    //解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //创建订单
                    createVoucherOrder(voucherOrder);
                    //确认消息
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1",record.getId());

                } catch (Exception e) {
                    log.error("处理订单异常");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
    //创建阻塞队列
/*    private BlockingQueue<VoucherOrder> orderTasks =new ArrayBlockingQueue<>(1024*1024);
    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    VoucherOrder voucherOrder = orderTasks.take();
                    createVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常");
                }
            }
        }
    }*/
    public Result seckillVoucher0(Long voucherId) {

        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        //执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),String.valueOf(orderId));
        //判断是否为0
        int r = result.intValue();
        if(r != 0){
            //不为0，代表没有购买资格
            return Result.fail(r == 1? "库存不足" : "不能重复下单");
        }
        //订单信息
        return Result.ok(orderId);
    }

    /**
     * 秒杀优惠券订单(无安全措施)
     * @param voucherId 订单ID
     * @return
     */
    @Transactional
    public Result seckillVoucher1(Long voucherId) {
//        1.根据id查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        2.判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//           秒杀未开始
            return Result.fail("秒杀尚未开始");
        }
//        3.判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//           秒杀已经结束
            return Result.fail("秒杀已经结束");
        }
//        4.判断库存是否充足
        if (seckillVoucher.getStock() < 1){
//           库存不足
            return Result.fail("库存不足");
        }
//        5.扣减库存
        UpdateWrapper<SeckillVoucher> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("stock",seckillVoucher.getStock() - 1);
        int update = seckillVoucherMapper.update(null, updateWrapper);
//        6.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
//        订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
//        用户id
        voucherOrder.setVoucherId(UserHolder.getUser().getId());
//        代金券id
        voucherOrder.setUserId(voucherId);
        save(voucherOrder);
//        7.返回订单id
        return Result.ok(orderId);
    }

    /**
     * 秒杀优惠券订单(乐观锁解决库存超卖(多线程并发安全))
     * @param voucherId
     * @return
     */
    @Transactional
    public Result seckillVoucher2(Long voucherId) {
//        1.根据id查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        2.判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//           秒杀未开始
            return Result.fail("秒杀尚未开始");
        }
//        3.判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//           秒杀已经结束
            return Result.fail("秒杀已经结束");
        }
//        4.判断库存是否充足
        if (seckillVoucher.getStock() < 1){
//           库存不足
            return Result.fail("库存不足");
        }
//        5.扣减库存
        boolean update = seckillVoucherService
                .update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0).update();  //设置库存大于0
        if (!update){
            return Result.fail("库存不足！");
        }

//        6.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
//        订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
//        用户id
        voucherOrder.setUserId(UserHolder.getUser().getId());
//        代金券id
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
//        7.返回订单id
        return Result.ok(orderId);
    }

    /**
     * 秒杀优惠券订单(在二的基础上，使用悲观锁实现一人一单功能)
     * @param voucherId
     * @return
     */
    public Result seckillVoucher3(Long voucherId) {
//        1.根据id查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        2.判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//           秒杀未开始
            return Result.fail("秒杀尚未开始");
        }
//        3.判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//           秒杀已经结束
            return Result.fail("秒杀已经结束");
        }
//        4.判断库存是否充足
        if (seckillVoucher.getStock() < 1) {
//           库存不足
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();
//        确保当用户id一样时，锁就会一样
        synchronized (userId.toString().intern()) {
//          createVoucherOrder不具有事务功能，需要获得当前对象的代理对象
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }
    }

    /**
     * 秒杀优惠券订单(调用分布式锁，实现一人一单功能优化，在集群部署下不会出现多线程并发的安全性问题)
     * @param voucherId
     * @return
     */
    public Result seckillVoucher4(Long voucherId) {
//        1.根据id查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        2.判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//           秒杀未开始
            return Result.fail("秒杀尚未开始");
        }
//        3.判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//           秒杀已经结束
            return Result.fail("秒杀已经结束");
        }
//        4.判断库存是否充足
        if (seckillVoucher.getStock() < 1) {
//           库存不足
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();
//        创建分布式锁对象
        SimpleRedisLock distriLock = new SimpleRedisLock( stringRedisTemplate,"order:" + userId);
        boolean isLock = distriLock.tryLock(1200L);
//        判断是否获取锁成功
        if (!isLock) {
//            获取锁失败
            return Result.fail("不允许重复下单");
        }
//        获取锁成功
//        createVoucherOrder不具有事务功能，需要获得当前对象的代理对象
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            distriLock.unlock();
        }
    }

    //    秒杀优惠券订单

    /**
     * 秒杀优惠券订单(Redisson实现分布式锁)
     * @param voucherId
     * @return
     */
    public Result seckillVoucher5(Long voucherId) {
//        1.根据id查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        2.判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//           秒杀未开始
            return Result.fail("秒杀尚未开始");
        }
//        3.判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//           秒杀已经结束
            return Result.fail("秒杀已经结束");
        }
//        4.判断库存是否充足
        if (seckillVoucher.getStock() < 1) {
//           库存不足
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();

        RLock lock = redissonClient.getLock("lock:order:" + userId);

        boolean isLock = lock.tryLock();
//        判断是否获取锁成功
        if (!isLock) {
//            获取锁失败
            return Result.fail("不允许重复下单");
        }
//        获取锁成功，创建订单
        try {
            return createVoucherOrder(voucherId);
        } finally {
            lock.unlock();
        }
    }

    //    扣减库存、创建订单
    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //查询用户是否已经购买过了
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("您已经购买过了！");
        }

//        6.扣减库存
        boolean update = seckillVoucherService
                .update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0).update();
        if (!update) {
            return Result.fail("库存不足！");
        }

//        7.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
//        订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
//        用户id
        voucherOrder.setUserId(userId);
//        代金券id
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
//        8.返回订单id
        return Result.ok(orderId);
    }

    /**
     * 秒杀优惠券订单（阻塞队列异步）
     * @param voucherId
     * @return
     */
    public Result seckillVoucher6(Long voucherId) {

        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString());
        //判断是否为0
        int r = result.intValue();
        if(r != 0){
            //不为0，代表没有购买资格
            return Result.fail(r == 1? "库存不足" : "不能重复下单");
        }
        //2.2 为0，有购买资格，把下单信息保存到阻塞队列
        long orderId = redisIdWorker.nextId("order");
        //订单信息
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        //orderTasks.add(voucherOrder);
        return Result.ok(orderId);
    }

    /**
     * 秒杀优惠券订单（消息队列异步——RabbitMq）
     * @param voucherId
     * @return
     */
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString());
        //判断是否为0
        int r = result.intValue();
        if(r != 0){
            //不为0，代表没有购买资格
            return Result.fail(r == 1? "库存不足" : "不能重复下单");
        }
        //2.2 为0，有购买资格，把下单信息保存到消息队列
        long orderId = redisIdWorker.nextId("order");
        //订单信息
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        //添加到消息队列中
        mqSender.sendSeckillMessage(JsonUtil.object2JsonStr(voucherOrder));
        return Result.ok(orderId);
    }

    public void createVoucherOrder(VoucherOrder voucherOrder) {
            //一人一单
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        //创建锁
        RLock redisLock = redissonClient.getLock("lock:order:" + userId);

        boolean isLock = redisLock.tryLock();
        if(!isLock){
            log.error("不允许重复下单！");
            return ;
        }

        try {
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                log.error("不允许重复下单！");
                return ;
            }
            //5.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();
            if (!success) {
                log.error("不允许重复下单！");
                return ;
            }
            //6.创建订单

            save(voucherOrder);
        } finally {
            redisLock.unlock();
        }
    }


    /*public  Result createVoucherOrder(Long voucherId) {
        //一人一单
        Long userId = UserHolder.getUser().getId();
        synchronized (userId.toString().intern()) {
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                return Result.fail("用户已购买过一次！");
            }
            //5.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();
            if (!success) {
                return Result.fail("库存不足");
            }
            //6.创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);

            voucherOrder.setUserId(userId);
            voucherOrder.setVoucherId(voucherId);
            save(voucherOrder);
            //7.返回订单id
            return Result.ok(orderId);
        }
    }*/
    /*public Result seckillVoucher(Long voucherId) {

        //1.查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2.判断秒杀是否开始
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始");
        }
        //3.判断秒杀是否已经结束
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        //4.判断库存是否充足
        if(voucher.getStock()<1){
            return Result.fail("库存不足！");
        }
        return createVoucherOrder(voucherId);
    }

    @Transactional
    public  Result createVoucherOrder(Long voucherId) {
        //一人一单
        Long userId = UserHolder.getUser().getId();
        //创建锁
        RLock redisLock = redissonClient.getLock("lock:order:" + userId);

        boolean isLock = redisLock.tryLock();
        if(!isLock){
            return Result.fail("不允许重复下单");
        }

        try {
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                return Result.fail("用户已购买过一次！");
            }
            //5.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();
            if (!success) {
                return Result.fail("库存不足");
            }
            //6.创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);

            voucherOrder.setUserId(userId);
            voucherOrder.setVoucherId(voucherId);
            save(voucherOrder);
            //7.返回订单id
            return Result.ok(orderId);
        } finally {

            redisLock.unlock();
        }
    }*/
}/*
    public  Result createVoucherOrder(Long voucherId) {
        //一人一单
        Long userId = UserHolder.getUser().getId();
        SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate, "order:" + userId);
        boolean isLock = redisLock.tryLock(1200);
        if(!isLock){
            return Result.fail("不允许重复下单");
        }

        try {
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                return Result.fail("用户已购买过一次！");
            }
            //5.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();
            if (!success) {
                return Result.fail("库存不足");
            }
            //6.创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);

            voucherOrder.setUserId(userId);
            voucherOrder.setVoucherId(voucherId);
            save(voucherOrder);
            //7.返回订单id
            return Result.ok(orderId);
        } finally {

            redisLock.unlock();
        }*/